package com.hm.service.config.quartz;

import com.hm.service.config.constant.DBConfig;
import com.hm.service.utils.HardwareUtils;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.HashMap;
import java.util.Properties;

@Configuration
public class QuartzConfig {

    private static final Logger logger = LoggerFactory.getLogger(QuartzConfig.class);

    @Autowired
    JobFactory jobFactory;

    @Bean(name = {"StdSchedulerFactory"})
    public SchedulerFactoryBean stdSchedulerFactory() {
        try {
            logger.warn("=======>QuartzConfig初始化了<=======");
            SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
            StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
            Properties props = getProperties();
            schedulerFactory.initialize(props);
            schedulerFactoryBean.setJobFactory(jobFactory);
            schedulerFactoryBean.setSchedulerFactory(schedulerFactory);
            return schedulerFactoryBean;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private Properties getProperties() {
        Properties props = new Properties();
        //调度标识名 集群中每一个实例都必须使用相同的名称
        props.put("org.quartz.scheduler.instanceName", "MainScheduler");
        //调度器实例的唯一标识符,集群模式要唯一
        props.put("org.quartz.scheduler.instanceId", "AUTO");
        //---------------jobStore配置----------------
        //是否启用集群支持
        props.put("org.quartz.jobStore.isClustered", "true");
        //JobStore类(数据保存方式为数据库持久化)
        props.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
        //集群检查间隔时间（单位为毫秒）
        props.put("org.quartz.jobStore.clusterCheckinInterval", "20000");
        //信息保存时间 默认值60秒
        props.put("org.quartz.jobStore.misfireThreshold", "60000");
        //数据库驱动程序委托类，用于不同的数据库
        props.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.StdJDBCDelegate");
        //数据源名称，指定数据源配置的名称(可以随意，对应上即可)
        props.put("org.quartz.jobStore.dataSource", "myDS");
        //表的前缀QRTZ_开头
        props.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
        //---------------数据库配置----------------
        int cores = HardwareUtils.getCores();
        int threadCount = (cores == 0 ? 1 : cores * 10);
        logger.warn("处理器核心数================>{}", cores);
        //数据源的具体配置参数
        String url = DBConfig.ds2.get("url");
        String Username = DBConfig.ds2.get("Username");
        String Password = DBConfig.ds2.get("Password");
        String DriverClassName = DBConfig.ds2.get("DriverClassName");
        props.put("org.quartz.dataSource.myDS.URL", url);
        props.put("org.quartz.dataSource.myDS.user", Username);
        props.put("org.quartz.dataSource.myDS.password", Password);
        props.put("org.quartz.dataSource.myDS.driver", DriverClassName);
        props.put("org.quartz.dataSource.myDS.maxConnections", String.valueOf(threadCount));
        //---------------线程池----------------
        //线程池类，默认为 org.quartz.simpl.SimpleThreadPool
        props.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
        //线程池中的线程数量
        props.put("org.quartz.threadPool.threadCount", cores == 0 ? 1 : String.valueOf(threadCount));
        //设置线程的优先级（最大为java.lang.Thread.MAX_PRIORITY 10，最小为Thread.MIN_PRIORITY 1，默认为5）
        props.put("org.quartz.threadPool.threadPriority", String.valueOf(Thread.NORM_PRIORITY));
        return props;
    }
}
